package com.yjy.fuyao.stu.controller.admin;


import com.alibaba.excel.EasyExcel;
import com.yjy.fuyao.stu.client.OssFileClient;
import com.yjy.fuyao.stu.entity.Subject;
import com.yjy.fuyao.stu.entity.SubjectTree;
import com.yjy.fuyao.stu.entity.dto.ExcelSubjectDTO;
import com.yjy.fuyao.stu.service.SubjectService;
import com.yjy.fuyao.utils.exception.BusinessException;
import com.yjy.fuyao.utils.result.R;
import com.yjy.fuyao.utils.result.ResponseEnum;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 课程科目 前端控制器
 * </p>
 *
 * @author yjy
 * @since 2021-08-15
 */
@RestController
@RequestMapping("/admin/stu/subject")
public class AdminSubjectController {
    @Resource
    private SubjectService subjectService;

    @Resource
    private OssFileClient ossFileClient;

    @ApiOperation("Excel批量导入数据字典")
    @PostMapping("/import")
    public R batchImport(
            @ApiParam(value = "excel文件",required = true)
            @RequestParam("file")
                    MultipartFile file,
            @ApiParam(value = "模块", required = true)
            @RequestParam("module") String module
    ){
        try {
            InputStream inputStream = file.getInputStream();
            subjectService.importData(inputStream);
            R result = ossFileClient.upload(file, module);
            return result;
        } catch (Exception e) {
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR,e);
        }
    }

    /**
     * 文件下载（失败了会返回一个有部分数据的Excel）
     * <p>
     * 1. 创建excel对应的实体对象 参照{@link ExcelSubjectDTO}
     * <p>
     * 2. 设置返回的 参数
     * <p>
     * 3. 直接写，这里注意，finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
     */
    @ApiOperation(value = "文件导出")
    @GetMapping("export")
    public void export(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("mysubject", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ExcelSubjectDTO.class).sheet("课程信息").doWrite(subjectService.exportData());
    }

    @ApiOperation("根据上级id获取子节点数据列表")
    @GetMapping("/listByParentId/{parentId}")
    public R listByParentId(
            @ApiParam(value = "上级节点id",required = true)
            @PathVariable
                    Long parentId){
        List<Subject> list = subjectService.listByParentId(parentId);
        return R.ok().data("list",list);
    }

    @ApiOperation("获取所有的课程类型，并按照类型进行封装")
    @GetMapping("/list")
    public R listAll(){
        List<SubjectTree> list = subjectService.listAll();
        return R.ok().data("list",list);
    }

}

